package com.xcc.core.netty.server;


import java.math.BigInteger;

import com.xcc.core.netty.manager.ManagerChannel;
import com.xcc.core.netty.model.LengthModel;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 版权：
 * <简述>
 * <详细描述> 用户端服务器
 * @author   xcc
 * @version  $Id$
 * @since
 * @see
 */
public class ServerLengthHandler extends SimpleChannelInboundHandler<LengthModel> {



    @Override
    public void channelActive(ChannelHandlerContext ctx)
        throws Exception {
        //  int id=Integer.parseInt(ctx.channel().id().asShortText(), 16);
        int   id=  new BigInteger(ctx.channel().id()
            .asShortText(), 16).intValue();
        System.out.println("内部端连接"+id);
        ManagerChannel.getAllClient().put("3389", ctx.channel());
        //告诉发送放客户端id
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LengthModel msg)
        throws Exception {
        String connectId=new String(msg.getBs());
           System.out.println(connectId);
        if(connectId.contains("connected")) {
            Channel ch=ctx.channel();
            System.out.println("发送给真服务id"+connectId.split("&")[1]);
            ManagerChannel.getChannelmapper().put(msg.getId()+"",connectId.split("&")[1]);
            System.out.println("内部系统连接成功");
        }else {
            //外部通道
            System.out.println("发送给客户ID："+msg.getId());
            Channel ch=ManagerChannel.getClientChannel2(msg.getId()+"");
            ByteBuf buf=Unpooled.copiedBuffer(msg.getBs());
            System.out.print("3389服务发送客户端数据："); 
            for(byte b:msg.getBs()) {
                System.out.print((0xff&b)+" ");
            }
            System.out.println();
            if(ch.isActive()) {
                ch.writeAndFlush(buf); 
            }else {
                System.out.println("客户端已死");
            }
           


        }


    }

}
